package main

import (
	"fmt"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	// 创建客户端配置
	config, err := clientcmd.BuildConfigFromFlags("", "../config/kubeconfig")
	if err != nil {
		panic(err)
	}
	// 创建客户端
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}
	// fmt.Println("客户端创建成功：", clientset)
	// 创建informer
	factory := informers.NewSharedInformerFactory(clientset, 0)
	// 获取资源的informer
	// pod
	podInformer := factory.Core().V1().Pods().Informer()
	// 从缓存中，监听资源的变化（新增、修改、删除）
	podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) { // 监听新增pod
			// 断言接收到的obj是否为pod
			pod := obj.(*corev1.Pod)
			fmt.Println("新增了一个Pod：", pod.Name)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			oldPod := oldObj.(*corev1.Pod)
			// newPod := newObj.(*corev1.Pod)
			fmt.Printf("更新了Pod：%v \n", oldPod.Name)
		},
		DeleteFunc: func(obj interface{}) {
			pod := obj.(*corev1.Pod)
			fmt.Println("删除了Pod：", pod.Name)
		},
	})
	// 启动Informer
	stopper := make(chan struct{})
	go factory.Start(stopper)

	// 等待Infomer启动完成(等待缓存同步数据)
	factory.WaitForCacheSync(stopper)

	// 限制主程序
	select {}
}
